package cn.zch.soft.util.http.okhttpclient;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.http.Header;

import java.util.List;
/**
 * @author zchcpywin10
 */
@Slf4j
public class OkHttpClientUtil {
  private OkHttpClientUtil() {}
  public static final OkHttpClient OK_HTTP_CLIENT = new OkHttpClient().newBuilder().build();
  /**
   *
   */
  public static String doRequest(String url, String requestMethod, RequestBody requestBody, List<Header> requestHeaders) {
    String responseBodyStr = null;
    ResponseBody body = null;
    try {
      if (null == requestMethod || "".equals(requestMethod)) {
        requestMethod = "GET";
      }
      if (null == url || "".equals(url)) {
        log.warn("url can not be empty");
        return null;
      }
      Request.Builder requestBuilder = new Request.Builder();
      requestBuilder.url(url);
      requestBuilder.method(requestMethod, requestBody);
      if (null != requestHeaders && !requestHeaders.isEmpty()) {
        for (Header requestHeader : requestHeaders) {
          requestBuilder.addHeader(requestHeader.getName(), requestHeader.getValue());
        }
      }
      Request request = requestBuilder.build();
      Response response = OK_HTTP_CLIENT.newCall(request).execute();
      body = response.body();
      if (null != body) {
        responseBodyStr = body.string();
      }
    }
    catch (Exception e) {
      log.error(e.getLocalizedMessage(), e);
    }
    finally {
      if (null != body) {
        body.close();
      }
    }
    return responseBodyStr;
  }
}
